package cn.buk.qms.web;

import cn.buk.api.azure.BlobService;
import cn.buk.common.JsonResult;
import cn.buk.qms.config.UploadStatus;
import cn.buk.tms.entity.order.OrderAttachment;
import cn.buk.qms.service.EnterpriseService;
import cn.buk.qms.service.FlightCharterService;
import cn.buk.qms.service.FlightOrderService;
import org.apache.commons.lang3.StringUtils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author yfdai
 * @date 2017/1/20
 */
@RestController
@RequestMapping("/upload")
public class UploadController extends BaseController {

  private static final Logger logger = LogManager.getLogger(UploadController.class);

  @Autowired
  private FlightCharterService flightCharterService;

  @Autowired
  private EnterpriseService enterpriseService;

  @Autowired
  private FlightOrderService flightOrderService;

  @RequestMapping(value = "/")
  public JsonResult uploadFile(HttpServletRequest request, HttpServletResponse response,
                               MultipartFile upfile,
                               @RequestParam(value = "orderId", defaultValue = "0") final int orderId,
                               @RequestParam(value = "orderType", defaultValue = "0") final int orderType,
                               @RequestParam(value = "fileDesc", defaultValue = "") final String fileDesc
  ) throws IOException {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);
//        final String fileName = new String(upfile.getOriginalFilename().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
    final String originalFilename = upfile.getOriginalFilename();
    int lastIndexOf = originalFilename.lastIndexOf(".");
    //获取文件的后缀名
    String suffix = originalFilename.substring(lastIndexOf);
    final String fileName = enterpriseId + "_" + System.currentTimeMillis() + "." + suffix;

    final String contentType = upfile.getContentType();
    final long fileSize = upfile.getSize();
    logger.info(String.format("%s,%s,%s,%d", upfile.getName(), fileName, contentType, fileSize));

    //Now do something with file...

    String filePath = System.getProperty("java.io.tmpdir") + File.separator;
//        File outputFile = new File(filePath + fileName);
    File outputFile = new File(filePath, fileName);
    logger.info(filePath + fileName);
    FileCopyUtils.copy(upfile.getBytes(), outputFile);

    Optional<BlobService> opt = enterpriseService.createBlobService(enterpriseId);

    if (opt.isEmpty()) {
      return JsonResult.createJsonResult(-1, "请先配置存储参数");
    }

    final String containerName = enterpriseService.getBlobStorageContainerName(enterpriseId);
    if (StringUtils.isEmpty(containerName)) {
      return JsonResult.createJsonResult(-2, "缺少容器名称");
    }

    String blobName = opt.get().uploadLocalFile(containerName, filePath + fileName);

    //保存上传文件名和BLOB文件名的映射
    int retCode = enterpriseService.saveFileNameMapping(enterpriseId, getUsername(request), originalFilename, blobName, contentType, fileSize);

    JsonResult jsonResult = new JsonResult();
    jsonResult.setStatus("OK");
    jsonResult.setDesc("上传成功：" + blobName);
    jsonResult.setReturnCode(retCode);

    if (retCode > 0 && orderId > 0) {
        //保存订单附件信息
        List<OrderAttachment> attachments = new ArrayList<>();
        var t = new OrderAttachment();
        attachments.add(t);
        t.setBlobId(retCode);
        t.setDescription(fileDesc);
        t.setFileName(originalFilename);
        flightOrderService.saveFlightOrderAttachment(enterpriseId, username, orderId, orderType, attachments);
    }

    return jsonResult;
  }

  /**
   * 这里是获取上传文件状态信息的访问接口
   *
   * @param session
   * @return
   */
  @ResponseBody
  @RequestMapping("/uploadStatus")
  public UploadStatus getStatus(HttpSession session) {
    return (UploadStatus) session.getAttribute("upload_status");
  }

  @RequestMapping(value = "/excel")
  public JsonResult uploadExcel(MultipartFile upfile, RedirectAttributes redirectAttributes,
                                HttpServletResponse response, HttpServletRequest request,
                                @RequestParam(value = "fileContentType", required = false) String fileContentType,
                                @RequestParam(value = "supplierId", defaultValue = "0") int supplierId,
                                @RequestParam(value = "formatNo", defaultValue = "1") int formatNo
  ) throws IOException {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    JsonResult jsonResult = new JsonResult();

    //Now do something with file...
    String fileName = new String(upfile.getOriginalFilename().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

    String filePath = System.getProperty("java.io.tmpdir");
    File outputFile = new File(filePath + fileName);
    FileCopyUtils.copy(upfile.getBytes(), outputFile);

    int importCount = 0;

    try {
      importCount = flightCharterService.importTicketNo(enterpriseId, username, filePath + fileName, supplierId, formatNo);
    } catch (RuntimeException ex) {
      logger.error(ex.getMessage());
      importCount = -100;
    }

    if (importCount > 0) {
      jsonResult.setStatus("OK");
      jsonResult.setDesc("导入 " + importCount + " 票号");
    } else {
      jsonResult.setStatus("ER");
      jsonResult.setErrcode(importCount);
    }

    return jsonResult;
  }
}
